from typing import List, Optional
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete
from models.attachment import Attachment
from schemas.attachment import AttachmentCreate 
from log import log_info, log_error

async def create_attachment(
    db: AsyncSession,
    attachment: AttachmentCreate,
    file_path: str
) -> Attachment:
    """创建新的附件记录"""
    try:
        db_attachment = Attachment(
            compliance_item_id=attachment.compliance_item_id,
            name=attachment.name,
            path=file_path,
            type=attachment.type,
            size=attachment.size
        )
        db.add(db_attachment)
        await db.commit()
        await db.refresh(db_attachment)
        log_info(f"Created attachment: {db_attachment.id}")
        return db_attachment
    except Exception as e:
        log_error(f"Error creating attachment: {str(e)}")
        raise

async def get_attachment(
    db: AsyncSession,
    attachment_id: UUID
) -> Optional[Attachment]:
    """获取指定ID的附件"""
    try:
        result = await db.execute(
            select(Attachment)
            .where(Attachment.id == attachment_id)
        )
        attachment = result.scalar_one_or_none()
        if attachment:
            log_info(f"Retrieved attachment: {attachment_id}")
        return attachment
    except Exception as e:
        log_error(f"Error retrieving attachment {attachment_id}: {str(e)}")
        raise

async def get_attachments_by_compliance_item(
    db: AsyncSession,
    compliance_item_id: UUID
) -> List[Attachment]:
    """获取指定合规项的所有附件"""
    try:
        result = await db.execute(
            select(Attachment)
            .where(Attachment.compliance_item_id == compliance_item_id)
        )
        attachments = result.scalars().all()
        return attachments
    except Exception as e:
        log_error(f"Error retrieving attachments for compliance item {compliance_item_id}: {str(e)}")
        raise

async def get_attachments_by_assessment_plan(
    db: AsyncSession,
    assessment_plan_id: UUID
) -> List[Attachment]:
    """获取指定评估计划的所有附件"""
    try:
        from models.complianceItem import ComplianceItem
        result = await db.execute(
            select(Attachment)
            .join(ComplianceItem, Attachment.compliance_item_id == ComplianceItem.id)
            .where(ComplianceItem.assessment_plan_id == assessment_plan_id)
        )
        attachments = result.scalars().all()
        return attachments
    except Exception as e:
        log_error(f"Error retrieving attachments for assessment plan {assessment_plan_id}: {str(e)}")
        raise

async def delete_attachment(
    db: AsyncSession,
    attachment_id: UUID
) -> bool:
    """删除指定的附件"""
    try:
        result = await db.execute(
            delete(Attachment)
            .where(Attachment.id == attachment_id)
        )
        await db.commit()
        if result.rowcount > 0:
            log_info(f"Deleted attachment: {attachment_id}")
            return True
        return False
    except Exception as e:
        log_error(f"Error deleting attachment {attachment_id}: {str(e)}")
        raise 